package com.saic.data.main;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;

import com.saic.data.dotask.DeleteTmpRecord;
import com.saic.data.dotask.UpdataDB;
import com.saic.data.job.ReadJob;
import com.saic.data.table.TableAction;
import com.saic.data.table.TableComparator;
import com.saic.data.table.TableFile;
import com.saic.data.table.TableUtil;
import com.saic.data.util.DBUtil;
import com.saic.data.util.FileUtil;
import com.saic.data.util.HbaseUtil;
import com.saic.data.util.ZookeeperUtil;

/**
 * @DESC:数据库操作：HBASE(TMP/DONE)/ORACLE
 * @author Xinshiyou
 */
public class HbaseCheck {
	
	//静态主函数用于检索Hbase任务并执行
	public static void main(String[] args) throws Exception {
		/** randomly to delay */
		int delay = new Random().nextInt(30);
		Thread.sleep(delay);

		ZookeeperUtil zooUtil = new ZookeeperUtil();
		Map<String, String> map = zooUtil.getProperties(zooUtil.rootpath);
		zooUtil.close();
		
		ReadJob readJob = new ReadJob();
		//查询需要更新记录的FTP_FILE
		List<TableFile> tList = new ArrayList<TableFile>();
		TableUtil.pm("HbaseCheck-main", "get UploadRecord list" );
		ResultScanner rScanner = HbaseUtil.QueryByConditionValue(TableUtil.configtab,TableUtil.configtabFamily,
				"fileStats", TableAction.UpdateDB.toString());
		//生成tablefile并排序
		for(Result result : rScanner){
			TableFile tFile = new TableFile(result, map);
			//if (tFile.gettConf().getTablename().compareTo("OATZ") == 0)
			tList.add(tFile);
		}
		rScanner.close();
		
		TableUtil.pm("HbaseCheck-main", "get ErrorStop list" );
		rScanner = HbaseUtil.QueryByConditionValue(TableUtil.configtab,TableUtil.configtabFamily,
				"fileStats", TableAction.ErrorStop.toString());
		//生成tablefile并排序
		for(Result result : rScanner){
			TableFile tFile = new TableFile(result, map);
			tList.add(tFile);
		}
		rScanner.close();
		
		TableComparator tc = new TableComparator();
		Collections.sort(tList,tc); 
		TableUtil.pm("HbaseCheck-main", tList.size()+" tables need UpRecord " );
		//操作tablefile
		doAction(readJob, tList);
		TableUtil.pm("HbaseCheck-main", tList.size()+" Update Finish " );

	}

	/**
	 * @DESC:根据Hbase表记录更新DB
	 * @param sqlUtil
	 * @param readJob
	 * @param tMap
	 * @param rScanner
	 * @throws Exception
	 */
	public static void doAction(ReadJob readJob,List<TableFile> tList) throws Exception {
		for(int i= tList.size()-1 ;i>=0;i--){
			TableFile tFile = tList.get(i);
			//IF Delete is needed compare streamNo 
			//System.out.println(tFile.gettConf().DBdelflag);
			DBUtil sqlUtil = new DBUtil();
			readJob.doReadJob(new UpdataDB(tFile, sqlUtil));
			/*if (tFile.checkStreamNo()){
				DBUtil sqlUtil = new DBUtil();
				readJob.doReadJob(new UpdataDB(tFile, sqlUtil));
			}
			else readJob.doReadJob(new DeleteTmpRecord(tFile));*/
		}

	}
}
